﻿using System;
using System.Collections.Generic;
using System.Web;
using Sgml;
using System.IO;
using System.Xml;

namespace MyWebPagesStarterKit.Utils
{
    /// <summary>
    /// Summary description for XhtmlHelper
    /// </summary>
    public class XhtmlHelper
    {
        private static string source;
        public XhtmlHelper(string html)
        {
            source = html;
        }

        public override string ToString()
        {
            try
            {
                bool upper = false;
                bool formatted = true;

                SgmlReader r = new SgmlReader();
                r.SetBaseUri(HttpContext.Current.Server.MapPath("."));
                r.DocType = "HTML";
                r.InputStream = new StringReader(source);
                if (upper) r.CaseFolding = CaseFolding.ToUpper;
                StringWriter sw = new StringWriter();
                XmlTextWriter w = new XmlTextWriter(sw);
                if (formatted)
                {
                    w.Formatting = Formatting.Indented;
                    r.WhitespaceHandling = WhitespaceHandling.None;
                }
                while (!r.EOF)
                {
                    w.WriteNode(r, true);
                }
                w.Close();
                return sw.ToString();
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
    }
}
